import json
import re

from django.contrib.auth import logout
from pymysql import *
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area, Address
from utils.views import LoginRequiredJSONMixin


class AreasView(View):
    def get(self, request):
        # 去缓存里面查数据
        province_list = cache.get('provinces')
        if not province_list:
            print('没有缓存省')
            # 1 去数据库查询所有省份数据
            try:
                areas = Area.objects.filter(parent=None)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': "获取省份失败，网络异常"})
            province_list = []
            for a in areas:
                province_list.append({"id": a.id, "name": a.name})
            # 把数据存到缓存
            cache.set('provinces', province_list, 3600 * 24 * 30)
        # 2.返回
        return JsonResponse({'code': 0, 'province_list': province_list})


class SubAreasView(View):
    def get(self, request, area_id):
        # 1 获取路径中的上一级的地区的id
        # 正则校验area_id
        subs = cache.get('cities_%s' % area_id)
        if not subs:
            print('没有缓存市或区')
            # 2 根据上一级的id获取下一级的数据(数据库操作)
            try:
                subareas = Area.objects.filter(parent_id=area_id)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': "获取市区失败，网络异常"})

            # 3 把下一级数据 做拼接
            subs = []
            for a in subareas:
                subs.append({'id': a.id, 'name': a.name})
            # 把数据存到缓存
            cache.set('cities_%s' % area_id, subs, 3600 * 24 * 30)
        # data.sub_data.subs

        # 4 返回给前端
        return JsonResponse({'code': 0, 'sub_data': {'subs': subs}})


class AddressView(LoginRequiredJSONMixin,View):
    def post(self,request):
        # - - 1 获取传来的参数
        body = request.body
        data_dict = json.loads(body)
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        # - 2 校 验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': "数据不全"})
        # - 3  使用Address模型类 添加数据
        try:
            address = Address.objects.create(user=request.user,
                                             title=receiver,
                                             receiver=receiver,
                                             province_id=province_id,
                                             city_id=city_id,
                                             district_id=district_id,
                                             place=place,
                                             mobile=mobile,
                                             tel=tel,
                                             email=email)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 505, 'errmsg': "保存失败"})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # - 4 返回成功信息
        return JsonResponse({'code': 0, 'errmsg': "ok", 'address': address_dict})

    def get(self, request):
        # 获取用户对象
        user = request.user
        # 获取所有地址
        # addresses = Address.objects.all(user=user)
        try:
            addresses = user.addresses.all().filter(is_deleted=False)
            # 创建一个空列表 存地址的字典数据
            address_dict_list = []
            # 循环拼接字典 添加到列表里
            for address in addresses:
                address_dict = {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                }
                # - 3拼接列表
                address_dict_list.insert(0, address_dict)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 501, 'erramg': '查询失败'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_dict_list,
                             'default_address_id': request.user.default_address})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        user = request.user
        # 设置默认地址
        try:
            user.default_address = address_id
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'erramg': '设置默认地址失败'})

        return JsonResponse({'code': 0, 'erramg': '设置默认地成功'})


class UpdateDestroyAddressView(View):
    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})
                # 判断地址是否存在,并更新地址信息
            try:
                Address.objects.filter(id=address_id).update(
                    user=request.user,
                    title=receiver,
                    receiver=receiver,
                    province_id=province_id,
                    city_id=city_id,
                    district_id=district_id,
                    place=place,
                    mobile=mobile,
                    tel=tel,
                    email=email
                )
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

                # 构造响应数据
            address = Address.objects.get(id=address_id)
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 响应更新地址结果
            return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # # 查询要删除的地址
            address = Address.objects.get(id=address_id)
            # # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()

        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            # # 查询要删除的地址
            address = Address.objects.get(id=address_id)
            # # 将修改标题为该后的
            address.title = title
            address.save()

        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '修改标题失败'})

        # 响应修改标题结果
        return JsonResponse({'code': 0, 'errmsg': '修改标题成功'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入密码不一致'})
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

            # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response
